#include "h/apue.h"
#include <dirent.h>
#include <time.h>
#include <errno.h>
#include <sys/wait.h>

#define TIME (time())

#define print_err(errno) (printf("%-15s %3d) is: %s\n",#errno, errno, strerror(errno)))

static void sig_int(int);

char * s_gets(char *, int);
void eatline(void);

#define BUFFSIZE 4096

int main(void)
{
    char buf[MAXLINE];
    pid_t pid;
    int status;

    _POSIX_SPORADIC_SERVER

    if (signal(SIGINT, sig_int) == SIG_ERR)
        err_sys("signal_error");

    printf("jack\n");
    printf("%%");
    while (s_gets(buf, MAXLINE) != NULL && buf[0] != 0)
    {
        if ((pid = fork()) < 0)
            err_sys("fork error");
        else if (pid == 0) {
            execlp(buf, buf, (char *)0);
            err_ret("couldn't execute: %s", buf);
            exit(127);
        }

        //parent
        if ( (pid == waitpid(pid, &status, 0)) < 0 )
            err_sys("waitpid error");

        printf("end%%");
    }

    return 0;
}

void sig_int(int signo)
{
    printf("interrupt\n%% ");
}

char * s_gets(char * str, int n)
{
    char * ret_val;
    char * find;

    if ((ret_val = fgets(str, n, stdin))) {
        find = strchr(str, '\n');
        if (find)
            *find = 0;
        else
            while (getchar() != '\n')
                ;
    }

    return ret_val;
}

void eatline(void)
{
    while (getchar() != '\n')
        ;
}
